<template>
  <el-dialog class="public-dialog" title="添加商品" width="90vw" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" />
      </template>

      <!-- 关联副店铺 -->
      <template #SubStoreName="{ row }">
        <template v-for="(item, i) in row.base_asin_store" :key="i">
          <VText :value="item.sub_store_name" :line="1" v-if="i < 2" />
        </template>
        <el-popover placement="left" :width="200" trigger="click" v-if="row.base_asin_store.length > 2">
          <div>
            <VText v-for="(item, i) in row.base_asin_store" :key="i" :value="item.sub_store_name" :line="1" />
          </div>
          <template #reference>
            <el-link type="primary" :underline="false">查看更多</el-link>
          </template>
        </el-popover>
      </template>
    </VTable>

    <template #footer>
      <el-button @click="handleClose"> 取消 </el-button>
      <el-button type="primary" :loading="loading" @click="submit"> 确认 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"

import XForm from "@/components/XForm/index.vue"
const emit = defineEmits(["submit", "handleClose"])

import { productChannelSkuList } from "@/api"
import { asinManagementManuallySync } from "@/api/base"

const props = defineProps({
  handleType: { type: String, default: "" }, // 操作类型
})

const modelValue = ref(false)
const data = reactive({
  loading: false,
})
const { loading } = toRefs(data)
const tableRef = ref()
const tableOptions = reactive({
  formConfig: {
    data: {
      timeRange: { type: "create_time", value: null, range: true },
      userRange: { type: "operations_id", value: null },
      skuRange: { type: "goods_sku", value: "" },
      asinRange: { type: "asin", value: "" },
    },
  },
  height: 600,
  columns: [
    { type: "checkbox", width: "40" },
    { field: "site", title: "站点", width: "100" },
    { field: "shop_name", title: "店铺", width: "200" },
    {
      field: "product_name",
      title: "商品名称",

      slots: {
        default: ({ row }) => <VText value={row.product_name} line={1} />,
      },
    },

    {
      field: "product_en_name",
      title: "平台产品标题",

      slots: {
        default: ({ row }) => {
          return (
            <div class="flex items-center">
              {row.is_sync_title == 1 ? (
                <el-tooltip effect="dark" content="已停止同步Listing平台标题！！" placement="top-start">
                  <svg-icon class="base-red-color" icon-class="hint_cover2"></svg-icon>
                </el-tooltip>
              ) : (
                ""
              )}
              <VText value={row.product_en_name} line={1} />
            </div>
          )
        },
      },
    },

    { field: "asin", title: "ASIN", width: "120" },
    { field: "platform_sku", title: "渠道SKU", width: "160" },
    { field: "goods_sku", title: "系统SKU", width: "120" },
    {
      field: "operator",
      title: "状态",
      width: "120",
      slots: {
        default: ({ row }) => <VStatus value={row.status == 0} />,
      },
    },
    { field: "operator_user_id_text", width: "140", title: "操作运营人员" },
    { field: "operations_personnel", width: "120", title: "销售人员" },
  ],

  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    ajax: {
      query: async ({ page, form }) => {
        let params = {
          ...initForm(form),
          ...page,
        }
        let res = await productChannelSkuList(params)
        return res
      },
    },
  },
})

import { getShopOptions } from "@/api/index.js"
onMounted(async () => {
  const shopRes = await getShopOptions({ platform_ids: [2] })
  originOption.value.shopOpt = shopRes.data.map((n) => ({
    label: n.shop_name,
    value: n.shop_id,
  }))
})
const originOption = ref({})
const formOption = ref({})
const fieldList = ref([
  {
    field: "shop_id",
    type: "select",
    originField: "shopOpt",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "Asin店铺" },
    style: { width: "200px" },
  },

  {
    field: "timeRange",
    type: "dateTimeRangeNorm",
    select: [{ label: "创建时间", value: "create_time" }],
    style: { width: "360px" },
  },
  {
    field: "userRange",
    type: "cascaderNew",
    selectStyle: { width: "140px" },
    select: [
      { label: "开发人员", value: "developer_id" },
      { label: "销售人员", value: "operations_id" },
      { label: "操作运营人员", value: "operator_user_id" },
    ],
    style: { width: "200px" },
  },

  {
    field: "skuRange",
    placeholder: "可批量搜索",
    type: "textarea",
    select: [
      { label: "SKU", value: "goods_sku" },
      { label: "自定义SKU", value: "custom_sku" },
      { label: "SPU", value: "spu" },
    ],
    style: { width: "200px" },
  },
  {
    field: "asinRange",
    placeholder: "可批量搜索",
    type: "textarea",
    select: [
      { label: "渠道SKU", value: "platform_sku" },
      { label: "ASIN", value: "asin" },
      { label: "UPC", value: "upc" },
    ],
    style: { width: "200px" },
  },

  {
    field: "status",
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "启用", value: 0 },
        { label: "禁用", value: 1 },
      ],
    },
    style: { width: "120px" },
  },

  {
    field: "is_sync_title",
    type: "select",
    options: {
      placeholder: "是否同步Listing标题",
      data: [
        { label: "是", value: 0 },
        { label: "否", value: 1 },
      ],
    },
    style: { width: "120px" },
  },
])
const submit = () => {
  let checkboxRecords = tableRef.value.$table.getCheckboxRecords()
  if (!checkboxRecords.length) {
    return ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
  }

  ElMessageBox.confirm(`此操作将 同步 ${checkboxRecords.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      let params = {
        channel_sku_id: checkboxRecords.map((v) => v.id),
      }
      asinManagementManuallySync(params).then((res) => {
        ElMessage.success("操作成功")
        emit("submit", checkboxRecords)
        handleClose()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
const handleClose = () => {
  tableRef.value.$table.reloadData([])
  nextTick(() => {
    modelValue.value = false
  })
}

import { getEnum, getAmazonSite } from "@/utils/enumUtils"
// const getOption = async () => {
//   let keys = ["Base.BaseAsinList.ActivityStatusEnum", "Base.BaseAsinList.StatusEnum"]
//   const data = await getEnum(keys)
//   keys.forEach((key) => {
//     originOption.value[key] = data[key]
//   })
//   originOption.value.amazonSite = (await getAmazonSite()).map((v) => ({ label: v.label, value: v.label }))
// }

const open = (type, form = {}) => {
  modelValue.value = true
  setTimeout(() => {
    nextTick(() => {
      // tableRef.value.$table.loadColumn(columns)
      tableRef.value.$table.setAllCheckboxRow()
      tableRef.value.query()
    })
  }, 100)
}

const initForm = (form) => {
  let keys = ["goods_sku", "custom_sku", "spu", "platform_sku", "asin", "upc"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v?.trim())
    form[key] = form[key]?.map((v) => v?.trim())
  })
  form.platform = "amazon"
  return form
}
defineExpose({
  open,
})
</script>
<style lang="scss" scoped></style>
